<template>
    <div class="layout-header-user">
        <el-popover
            v-model:visible="state.showUserInfoPopover"
            placement="bottom-end"
            :hide-after="0"
            :width="220"
            trigger="click"
            popper-class="user-info-box">
            <template #reference>
                <el-button style="width: 220px">
                    {{ userStore.user.nick_name }}
                </el-button>
            </template>
            <div class="user-info-menu-list">
                <div class="user-info-menu-item">
                    <el-button type="info" class="menu-btn">{{ userStore.user.nick_name }}</el-button>
                </div>
                <div class="user-info-menu-item">
                    <el-button type="primary" class="menu-btn" @click="onChangePwd">修改密码</el-button>
                </div>
                <div class="user-info-menu-item">
                    <el-button type="danger" class="menu-btn" @click="onLogout">注销</el-button>
                </div>
            </div>
        </el-popover>
        <ChangePasswordDialog ref="changePasswordRef"></ChangePasswordDialog>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessageBox } from 'element-plus';
import api from '@/api';
import { PUBLIC_PATH } from '@/constant';
import { useTokenStore, useUserStore } from '@/stores';
import { useRouter } from 'vue-router';
import ChangePasswordDialog from '@/components/changepassword/ChangePasswordDialog.vue';

const router = useRouter();
const userStore = useUserStore();
const tokenStore = useTokenStore();
const changePasswordRef = ref();
const state = reactive({
    showUserInfoPopover: false,
});

const onChangePwd = () => {
    changePasswordRef.value.open();
};

const onLogout = () => {
    ElMessageBox.confirm('确认退出系统？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        customStyle: {
            top: '15%',
            position: 'absolute',
            width: '420px',
            'margin-left': '-210px',
        },
    }).then(() => {
        api.post('/api/web/logout')
            .then(() => {
                userStore.remove();
                tokenStore.remove();
                router.push(PUBLIC_PATH);
            })
            .catch(() => {
                userStore.remove();
                tokenStore.remove();
                router.push(PUBLIC_PATH);
            });
    });
};
</script>

<style scoped lang="scss">
.user-info-box {
    .user-info-menu-list {
        display: flex;
        flex-direction: column;
    }
    .user-info-menu-item {
        width: 200px;
        margin-bottom: 15px;
        .menu-btn {
            width: 100%;
        }
    }
}
</style>
